package LeedCode_BinaryTree;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 阿宾
 * Date: 2024-11-20
 * Time: 21:26
 */
public class Demo2 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 判断两棵树是否是相同的树
     * @param p
     * @param q
     * @return
     */
    public static boolean isSameTree(TreeNode p, TreeNode q) {
        //判断空树
        if(p == null && q == null){
            return true;
        }
        //判断一个为空，一个不为空
        if(p == null || q == null){
            return false;
        }
        //都不空,判断值
        if(p.val != q.val){
            return false;
        }
        boolean ret1 = isSameTree(p.left,q.left);
        boolean ret2 = isSameTree(p.right,q.right);
        return ret1 && ret2;

    }
    //判断是否是子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        //如果root为空，则肯定没子树（在遍历过程中，root可能为空）
        if(root == null){
            return false;
        }
        //检查root和subRoot是否是相同的树
        if(isSameTree(root, subRoot)){
            return true;
        }
        //递归遍历左右子树
        boolean leftTree = isSubtree(root.left,subRoot);
        boolean rightTree = isSubtree(root.right,subRoot);
        //相同的子树可能在root的左子树，也可能在右子树
        return leftTree || rightTree;

    }
    public static void main(String[] args) {

    }
}
